package com.naxiangfish.cn.utils;

import android.util.Base64;

import com.naxiangfish.cn.constant.ConstantUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * 作者: 赵航
 * 创建时间: 2018/8/18 16:27
 * 描述:
 */
public class DesSecreat {
    private static final DesSecreat ourInstance = new DesSecreat();

    public static DesSecreat getInstance() {
        return ourInstance;
    }

    private DesSecreat() {

    }

    /**
     * 1.字符串的加密
     * 加密
     **/
    public String encryptPassword(String clearText) {
        try {
            DESKeySpec keySpec = new DESKeySpec(ConstantUtils.SAVEKEY.getBytes("UTF-8"));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(keySpec);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            String encrypedPwd = Base64.encodeToString(cipher.doFinal(clearText.getBytes("UTF-8")), Base64.DEFAULT);
            return encrypedPwd;
        } catch (Exception e) {
        }
        return clearText;
    }

    /**
     * 2.字符串的解密
     * 解密
     **/
    public String decryptPassword(String encryptedPwd) {
        try {
            DESKeySpec keySpec = new DESKeySpec(ConstantUtils.SAVEKEY.getBytes("UTF-8"));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(keySpec);
            byte[] encryptedWithoutB64 = Base64.decode(encryptedPwd, Base64.DEFAULT);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] plainTextPwdBytes = cipher.doFinal(encryptedWithoutB64);
            return new String(plainTextPwdBytes);
        } catch (Exception e) {
        }
        return encryptedPwd;
    }
}
